﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Anke.SHManage.Web.Areas.BM.Controllers
{
    [SkipLoginAttribute]
    public class PatientChargeController : Controller
    {
        private JavaScriptSerializer js = new JavaScriptSerializer();
        private string YBInterfaceType = ConfigurationManager.AppSettings["YBInterfaceType"].ToString();//2023-06-14 zch 医保接口方式 


        #region 保存病历收费信息 // 医保上线移植 2021-10-18 plq
        ///// <summary>
        ///// 保存病历收费信息
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult SavePatientCharge()
        //{
        //    string chargeStr = Request.Form["Charge"].ToString();
        //    string workCode = Request.Form["WorkCode"].ToString(); //工号
        //    string personName = Request.Form["PersonName"].ToString(); //姓名
        //    List<M_PatientChargeLog> charges = JsonHelper.GetJsonInfoBy<List<M_PatientChargeLog>>(chargeStr);//解析收费日志表
        //    if (charges == null)
        //        return Json(new { result = "ERROR", msg = "解析实体为空！" }, "appliction/json", JsonRequestBehavior.AllowGet);

        //    bool Success = false;

        //    //2014-12-04
        //    foreach (M_PatientChargeLog charge in charges)
        //    {
        //        string errorMsg = "";//返回消息
        //        MobileTaskBLL bll = new MobileTaskBLL();
        //        if (charge.Isvalid == true)
        //        {
        //            M_PatientChargeLog pchargeLog = null;
        //            M_PatientCharge pcharge = GetChargeInfo(charge);

        //            //增加收费主表信息
        //            if (bll.MobileSavePatientCharge(pcharge, pchargeLog, ref errorMsg))
        //            {
        //                Success = true;
        //            }
        //            else
        //                return Json(new { result = "ERROR", msg = "上传收费主表失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);

        //        }

        //        //20151210-收费日志表
        //        M_PatientCharge pchargeN = null;//20151210--设置收费主表为空
        //        charge.ID = System.Guid.NewGuid();//20151210--创建新ID
        //        charge.IMEI = "PAD";
        //        charge.IFArrearage = false;//是否欠费
        //        if (bll.MobileSavePatientCharge(pchargeN, charge, ref errorMsg))
        //        {
        //            Success = true;
        //        }
        //        else
        //            Success = false;
        //    }
        //    if (Success)
        //        return Json(new { result = "OK", msg = "上传收费成功！" }, "appliction/json", JsonRequestBehavior.AllowGet);
        //    else
        //        return Json(new { result = "ERROR", msg = "上传收费失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);

        //}

        /// <summary>
        /// 保存病历收费信息
        /// 医保上线移植 2021-10-18 plq
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SavePatientCharge()
        {
            try
            {
                string chargeStr = Request.Form["Charge"].ToString();
                string workCode = Request.Form["WorkCode"].ToString(); //工号
                string personName = Request.Form["PersonName"].ToString(); //姓名
                List<M_PatientChargeLog> charges = JsonHelper.GetJsonInfoBy<List<M_PatientChargeLog>>(chargeStr);//解析收费日志表
                if (charges == null)
                {
                    LogUtility.Error("PatientCharge/SavePatientCharge", "解析实体为空！");
                    return Json(new { result = "ERROR", msg = "解析实体为空！" }, "appliction/json", JsonRequestBehavior.AllowGet);
                }

                bool Success = false;

                string taskCode = "";//20210514
                int patientOrder = -1;//20210514 

                //20210517取任务编码和序号
                foreach (M_PatientChargeLog charge in charges)
                {
                    taskCode = charge.TaskCode;//20210514
                    patientOrder = charge.PatientOrder;//20210514 
                    break;
                }
                string errorMsgs = "";//返回消息

                P_UserBLL ubll = new P_UserBLL();
                P_User user = ubll.GetModelWithOutTrace(u => u.WorkCode == workCode).ToExtModle(); //查找用户名--20210426
                int userId = user.ID;

                //调用扣库存的方法
                bool retDelivery = SaveTaskDelivery(false, taskCode, patientOrder, userId, ref errorMsgs);
                if (!retDelivery)
                    return Json(new { result = "ERROR", msg = "自动出库失败！" + errorMsgs }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                if (retDelivery)
                {
                    //2014-12-04
                    foreach (M_PatientChargeLog charge in charges)
                    {
                        string errorMsg = "";//返回消息

                        charge.ChargeType = -1;//2021-10-12 zll 为了冗余收费主表的收费类型 //add2021-10-18 plq 医保上线移植
                        MobileTaskBLL bll = new MobileTaskBLL();
                        string TaskCode = charge.TaskCode;//20210426 
                        int PatientOrder = charge.PatientOrder;//20210426 
                        bool Isvalid = Convert.ToBoolean(charge.Isvalid);//20210426 

                        if (charge.Isvalid == true)
                        {
                            M_PatientChargeLog pchargeLog = null;
                            M_PatientCharge pcharge = GetChargeInfo(charge);

                            List<M_PatientChargeDetailLog> pchargeDetailLog = null;//2021-10-12 zll --收费子表日志表  //add2021-10-18 plq 医保上线移植
                            List<M_PatientChargeDetail> pchargeDetail = charge.PatientChargeDetail;//2021-10-12 zll  收费子表  //add2021-10-18 plq 医保上线移植

                            //增加收费主表和收费子表信息 //2021-10-18 plq 医保上线移植
                            if (bll.MobileSavePatientCharge(TaskCode, PatientOrder, pcharge, pchargeLog, pchargeDetail, pchargeDetailLog, Isvalid, ref errorMsg)) 
                            {
                                Success = true;
                            }
                            else
                            {
                                LogUtility.Error("PatientCharge/SavePatientCharge", "上传收费主表失败！任务编码：" + pcharge.TaskCode + ",病历序号：" + pcharge.PatientOrder);
                                return Json(new { result = "ERROR", msg = "上传收费主表失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);
                            }
                        }
                        //如果插入收费主表和收费子表信息成功，在操作收费主表和子表的日志表信息
                        if (Success)
                        {
                            //20151210-收费日志表
                            M_PatientCharge pchargeN = null;//20151210--设置收费主表为空
                            charge.ID = System.Guid.NewGuid();//20151210--创建新ID
                            charge.IMEI = "PAD";
                            charge.IFArrearage = false;//是否欠费

                            List<M_PatientChargeDetail> pChargeDetail = null;//20210426--收费子表
                            List<M_PatientChargeDetailLog> pChargeDetailLog = new List<M_PatientChargeDetailLog>();//20210426收费子表日志表

                            for (int L = 0; L < charge.PatientChargeDetail.Count; L++)
                            {
                                M_PatientChargeDetail chargeDetail = charge.PatientChargeDetail[L];
                                M_PatientChargeDetailLog cInfo = new M_PatientChargeDetailLog();
                                cInfo.ID = System.Guid.NewGuid();//--创建新ID
                                cInfo.TaskCode = chargeDetail.TaskCode;
                                cInfo.PatientOrder = chargeDetail.PatientOrder;
                                cInfo.ChargeOrder = L + 1;//收费序号
                                cInfo.ChargeDate = chargeDetail.ChargeDate;
                                cInfo.PaidMoney = chargeDetail.PaidMoney;
                                cInfo.ChargeType = chargeDetail.ChargeType;
                                cInfo.OrderNumber = chargeDetail.OrderNumber;
                                cInfo.IFRefund = chargeDetail.IFRefund;
                                cInfo.Isvalid = true;
                                pChargeDetailLog.Add(cInfo);
                            }

                            //2021-10-18 plq 医保上线移植
                            if (bll.MobileSavePatientCharge(TaskCode, PatientOrder, pchargeN, charge, pChargeDetail, pChargeDetailLog, Isvalid, ref errorMsg))
                            {
                                Success = true;
                            }
                            else
                            {
                                LogUtility.Error("PatientCharge/SavePatientCharge", "上传收费主表日志表失败！任务编码：" + TaskCode + ",病历序号：" + PatientOrder);
                                return Json(new { result = "ERROR", msg = "上传收费主表日志表/收费子表日志表失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);
                            }
                        }
                    }
                }
                if (Success)
                {
                    //UpdatePatientRecord(taskCode, patientOrder, personName);
                    return Json(new { result = "OK", msg = "上传收费成功！" }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    LogUtility.Error("PatientCharge/SavePatientCharge", "上传收费失败！");
                    return Json(new { result = "ERROR", msg = "上传收费失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("PatientCharge/SavePatientCharge", ex.Message);
                return Json(new { result = "ERROR", msg = "上传收费失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);
            }

        }

        /// <summary>
        /// 拼接指导医生姓名
        /// 2021-10-18 plq 医保上线移植
        /// </summary>
        /// <param name="taskCode"></param>
        /// <param name="patientOrder"></param>
        /// <param name="personName"></param>
        /// <returns></returns>
        [HttpPost]
        public Boolean UpdatePatientRecord(string taskCode, int patientOrder, string personName)
        {
            try
            {
                M_PatientRecordBLL bll = new M_PatientRecordBLL();
                if (bll.UpdatePatientRecord(taskCode, patientOrder, personName))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("PatientChargeController/UpdatePatientRecord", "程序异常：" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 上传发票号20160421
        [SkipLoginAttribute]
        public bool SaveFaPiaoNumber()
        {
            MobileTaskBLL bll = new MobileTaskBLL();

            string TaskCode = Request.Form["TaskCode"].ToString();
            int PatientOrder = int.Parse(Request.Form["PatientOrder"]);
            string FaPiaoNumber = Request.Form["FaPiaoNumber"].ToString();

            bool save = false;

            try
            {
                save = bll.UpdateFaPiaoNumber(TaskCode, PatientOrder, FaPiaoNumber);//更新发票号
                //2018-12-11 zch
                //I_InvoiceApplyListBLL alBLL = new I_InvoiceApplyListBLL();
                //I_InvoiceApplyList ainfo = alBLL.GetModelWithOutTrace(p => p.InvoiceNumber == FaPiaoNumber);
                //ainfo.isUsed = true;
                //alBLL.Modify(ainfo, "isUsed");
            }
            catch
            {
                save = false;
            }
            return save;
        }
        #endregion

        #region 20151210对接收的收费表转换
        private M_PatientCharge GetChargeInfo(M_PatientChargeLog charge)
        {
            M_PatientCharge pcharge = new M_PatientCharge();
            pcharge.TaskCode = charge.TaskCode;
            pcharge.PatientOrder = charge.PatientOrder;
            pcharge.Date = charge.Date;
            pcharge.InvoiceNumber = charge.InvoiceNumber;
            pcharge.PatientName = charge.PatientName;
            //pcharge.AddressStart = charge.AddressStart;
            //pcharge.AddressEnd = charge.AddressEnd;
            //pcharge.OutStationRoadCode = charge.OutStationRoadCode;
            pcharge.PointRoadCode = charge.PointRoadCode;
            pcharge.ArriveHospitalRoadCode = charge.ArriveHospitalRoadCode;
            //pcharge.ReturnStationRoadCode = charge.ReturnStationRoadCode;
            pcharge.OneWayKM = charge.ChargeKM;
            pcharge.ChargeKM = charge.ChargeKM;
            pcharge.CarFee = charge.CarFee;
            pcharge.WaitingFee = charge.WaitingFee;
            pcharge.EmergencyFee = charge.EmergencyFee;
            pcharge.DrugFeeTotal = charge.DrugFeeTotal;
            pcharge.ExamineFeeTotal = charge.ExamineFeeTotal;
            pcharge.ConsumableFeeTotal = charge.ConsumableFeeTotal;
            pcharge.MeasureFeeTotal = charge.MeasureFeeTotal;
            pcharge.ReceivableTotal = charge.ReceivableTotal;
            pcharge.PaidMoney = charge.PaidMoney;
            pcharge.ChargePerson = charge.ChargePerson;
            pcharge.IFArrearage = false;//是否欠费
            pcharge.TaskSD = charge.TaskSD;
            //pcharge.ReceivablesPaidInconsistentReasons = charge.ReceivablesPaidInconsistentReasons;
            //pcharge.BackUp1 = charge.BackUp1;
            pcharge.baidufei = charge.baidufei;
            pcharge.IMEI = "PAD";

            pcharge.PaidCarFee = charge.PaidCarFee; //2017-11-09 周志猛 添加车费实收
            pcharge.PaidPRFee = charge.PaidPRFee;//2017-11-09 周志猛 添加治疗费实收
            pcharge.ChargeType = charge.ChargeType; //2021-10-28 zll 
            return pcharge;
        }
        #endregion

        #region 20151210获取收费信息
        [HttpPost]
        public ActionResult GetPatientCharge()
        {
            int patientOrder = 1;
            string taskCode = Request.Form["TaskCode"].ToString();
            if (Request.Form["PatientOrder"] != "")
            {
                patientOrder = Convert.ToInt32(Request.Form["PatientOrder"]); //序号
            }
            MobileTaskBLL bll = new MobileTaskBLL();
            M_PatientCharge pcharge = null;
            //2021-10-25 zll 新增收费子表回传   目前没有电子支付  不做判断 //2021-12-06 plq 医保移植
            List<M_PatientChargeDetail> pcDetail = null;//20211025 收费子表信息
            bll.GetPatientChargeInfo(taskCode, patientOrder, out pcharge, out pcDetail);//获取收费信息
            return Json(new { success = true, pcharge = pcharge, pcDetail = pcDetail }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取病历信息--20151201注释
        //获取病历信息--20151201注释
        public void GetPatientRecordInfo(string TaskCode, string WorkID, out M_PatientRecord info, out M_PatientRecordAppend pra, out M_PatientRecordCPR prCPR)
        {
            M_PatientRecordBLL prBLL = new M_PatientRecordBLL();
            M_AttemperData result = prBLL.GetAttemperData(TaskCode, "");//根据任务编码获取调度信息

            info = new M_PatientRecord();//病历主表信息
            info.TaskCode = TaskCode;
            info.PatientOrder = 1;
            info.CallOrder = result.CallOrder;
            info.Name = result.Name;
            info.Sex = result.Sex;
            info.AgeType = "岁";
            info.ForHelpTelephone = result.ForHelpPhone;
            info.ContactTelephone = result.ContactTelephone;
            info.PatientVersion = result.AlarmType;
            info.OriginalTaskType = result.AlarmType;
            info.ForArea = result.Area;
            info.LocalAddress = result.LocalAddress;
            info.OutStationCode = result.StationCode;
            info.Station = result.Station;
            info.SendAddress = result.SendAddress;
            info.DrivingTime = result.DrivingTime;
            info.ArriveSceneTime = result.ArriveSceneTime;
            info.LeaveSceneTime = result.LeaveSceneTime;
            info.ArriveDestinationTime = result.ArriveDestinationTime;
            info.Driver = result.Driver;
            info.StretcherBearersI = result.StretcherBearers;
            info.DoctorAndNurse = result.Doctor + result.Nurse;
            P_UserBLL bll = new P_UserBLL();
            P_User user = bll.GetListBy(u => u.WorkCode == WorkID).Select(u => u.ToExtModle()).FirstOrDefault(); //查找用户名 密码
            info.AgentCode = user.ID.ToString();
            info.AgentWorkID = WorkID;
            info.AgentName = user.Name;
            info.BeginFillPatientTime = DateTime.Now;
            info.MedicalRecordGenerationTime = DateTime.Now;
            info.FormCompleteLogo = false;
            //obj.FormCompleteTime = null;
            info.ChargeOrder = 0;
            info.SubCenterIFSpotChecks = false;
            info.CenterIFSpotChecks = false;
            info.SubmitLogo = false;
            info.SubmitTime = null;
            info.MedicalStateCode = 0;
            info.LastUpdatePerson = user.Name;//填写病历的人员
            info.LastUpdateTime = DateTime.Now;
            info.CPRIFSuccess = "";//心肺复苏选择
            info.IFRefuseTreatment = "治疗记录";//是否拒绝治疗（救治记录）
            info.RescueType = "";//抢救类型(救治记录)
            info.IMEI = "PAD";//从PAD填写


            pra = new M_PatientRecordAppend();//
            pra.TaskCode = TaskCode;
            pra.PatientOrder = 1;

            prCPR = new M_PatientRecordCPR();//
            prCPR.TaskCode = TaskCode;
            prCPR.PatientOrder = 1;
            prCPR.CenterIFAuditForXFFS = false;
        }
        #endregion

        #region 20210909 sr 上传收费扣库存接口 //2021-10-18 plq 医保上线移植

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Boolean SaveTaskDelivery(bool isCheck, string taskCode, int patientOrder, int userId, ref string errorMsg)
        {
            try
            {
                string strURL = "";
                string responseText = "";
                strURL = ConfigurationManager.AppSettings["YBWebSaveTaskDelivery"].ToString();
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";
                // 参数经过URL编码
                StringBuilder sb = new StringBuilder();
                sb.Append("&isCheck=" + isCheck);
                sb.Append("&taskCode=" + taskCode);
                sb.Append("&patientOrder=" + patientOrder);
                sb.Append("&userId=" + userId);
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请求流
                System.IO.Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                // 关闭请求流
                writer.Close();
                System.Net.HttpWebResponse response;
                // 获得响应流
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseText = myreader.ReadToEnd();
                myreader.Close();
                //解析返回的实体
                ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                if (rinfo.status == "0")
                {
                    return true;
                }
                else
                {
                    errorMsg = rinfo.msg;
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("PatientChargeController/SaveTaskDelivery", "程序异常：" + ex.Message);
                return false;
            }
        }
        #endregion


        #region 202111296 获取医保诊断信息 异地医保 //2022-03-28 plq 从闵行移植
        [HttpPost]
        public ActionResult GetYBZdList()
        {
            int patientOrder = 1;
            string taskCode = Request.Form["TaskCode"].ToString();
            String code = Request.Form["Code"].ToString();
            if (code != null && code != "")
            {
                code = code.Substring(0, code.LastIndexOf(','));
            }
            if (Request.Form["PatientOrder"] != "")
            {
                patientOrder = Convert.ToInt32(Request.Form["PatientOrder"]); //序号
            }
            MobileTaskBLL bll = new MobileTaskBLL();
            List<M_ZICDNew> zdnos = null;
            string result = "Error";
            bll.GetYBZdList(taskCode, patientOrder, code, out zdnos, out result);//获取医保诊断信息
            return Json(new { result = result, msg = zdnos, YBInterfaceType = YBInterfaceType }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region 获取病历信息 //2022-03-28 plq 从闵行移植
        [HttpPost]
        public ActionResult GetAlarmReason()
        {
            try
            {
                int patientOrder = 1;
                string taskCode = Request.Form["taskCode"].ToString();
                if (Request.Form["patientOrder"] != "")
                {
                    patientOrder = Convert.ToInt32(Request.Form["patientOrder"]); //序号
                }
                M_PatientRecordBLL bll = new M_PatientRecordBLL();
                string retStr = bll.GetAlarmReason(taskCode, patientOrder);
                return Json(new { code = 0, message = retStr }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                LogUtility.Error("PatientChargeController.GetAlarmReason", ex.Message);
                return Json(new { code = 1, message = "获取失败！原因：" + ex.Message }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public ActionResult GetFirstImpressionCodes()
        {
            try
            {
                int patientOrder = 1;
                string taskCode = Request.Form["taskCode"].ToString();
                if (Request.Form["patientOrder"] != "")
                {
                    patientOrder = Convert.ToInt32(Request.Form["patientOrder"]); //序号
                }
                M_PatientRecordBLL bll = new M_PatientRecordBLL();
                string retStr = bll.GetFirstImpressionCodes(taskCode, patientOrder);
                return Json(new { code = 0, message = retStr }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                LogUtility.Error("PatientChargeController.GetFirstImpressionCodes", ex.Message);
                return Json(new { code = 1, message = "获取失败！原因：" + ex.Message }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

    }
}
